# coding: utf-8
from enum import Enum
from typing import Union

from PySide6.QtCore import Signal, Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout, QButtonGroup, QAbstractButton
from qeventmanager import qevent_manager
from qfluentwidgets import FlowLayout, PillPushButton

from common.server import BananaServer, BananaCategory
from components import CustomScrollArea, GridLayout, VideoCard
from ..tools import check_result


class CategoryInterface(QWidget):
    clicked = Signal(QAbstractButton)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)

        self.cateLayout, self.cateGroup = self.createSubLayout(BananaCategory.CATEGORYS)
        self.areaLayout, self.areaGroup = self.createSubLayout(BananaCategory.AREAS)
        self.yearLayout, self.yearGroup = self.createSubLayout(BananaCategory.YEARS)
        self.definitionLayout, self.definitionGroup = self.createSubLayout(BananaCategory.DEFINITIONS)
        self.durationLayout, self.durationGroup = self.createSubLayout(BananaCategory.DURATIONS)
        self.mosaicLayout, self.mosaicGroup = self.createSubLayout(BananaCategory.MOSAICS)
        self.langvoiceLayout, self.langvoiceGroup = self.createSubLayout(BananaCategory.LANGVOICES)
        self.orderbyLayout, self.orderbyGroup = self.createSubLayout(BananaCategory.ORDERBYS)

        self.__initWidgets()
        self.__initLayout()

    def __initWidgets(self):
        pass

    def __initLayout(self):
        self.verticalLayout.addLayout(self.cateLayout)
        self.verticalLayout.addLayout(self.areaLayout)
        self.verticalLayout.addLayout(self.yearLayout)
        self.verticalLayout.addLayout(self.definitionLayout)
        self.verticalLayout.addLayout(self.durationLayout)
        self.verticalLayout.addLayout(self.mosaicLayout)
        self.verticalLayout.addLayout(self.langvoiceLayout)
        self.verticalLayout.addLayout(self.orderbyLayout)

    def createSubLayout(self, data: Union[list, Enum]):
        if isinstance(data, Enum):
            data = data.value
        layout, group = FlowLayout(), QButtonGroup(self)
        all_btn = PillPushButton('全部', self)
        all_btn.setProperty('key', 0)
        all_btn.setChecked(True)
        layout.addWidget(all_btn)
        group.addButton(all_btn)

        item: dict
        for item in data:
            btn = PillPushButton(self)
            btn.setProperty('key', item['keyid'])
            btn.setText(item['value'])
            layout.addWidget(btn)
            group.addButton(btn)
        group.buttonClicked.connect(self.clicked)
        return layout, group

    def getCheckedCategory(self):
        cateid = self.cateGroup.checkedButton().property('key')
        areaid = self.areaGroup.checkedButton().property('key')
        yearid = self.yearGroup.checkedButton().property('key')
        definition = self.definitionGroup.checkedButton().property('key')
        duration = self.durationGroup.checkedButton().property('key')
        mosaic = self.mosaicGroup.checkedButton().property('key')
        langvoice = self.langvoiceGroup.checkedButton().property('key')
        orderby = self.orderbyGroup.checkedButton().property('key')
        return {
            'cateid': cateid,
            'areaid': areaid,
            'yearid': yearid,
            'definition': definition,
            'duration': duration,
            'mosaic': mosaic,
            'langvoice': langvoice,
            'orderby': orderby
        }


class ClassInterface(CustomScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.contentWidget = QWidget(self)
        self.contentLayout = QVBoxLayout(self.contentWidget)

        self.categotyInterface = CategoryInterface(self.contentWidget)
        self.gridLayout = GridLayout()

        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName("ClassInterface")
        self.setWidget(self.contentWidget)
        self.contentLayout.setContentsMargins(0, 0, 0, 0)
        self.contentLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.contentLayout.addWidget(self.categotyInterface)
        self.contentLayout.addLayout(self.gridLayout)

        self.categotyInterface.clicked.connect(self.onCategoryClicked)

    def init(self):
        if not self.isLoad:
            self.load()
            self.isLoad = True

    def load(self, **kwargs):
        qevent_manager.addTask(BananaServer.vod_listing, **kwargs, page=self.currentPage, slot=self.onResult)

    def onCategoryClicked(self, btn: QAbstractButton):
        self.currentPage = 1
        self.gridLayout.takeAllWidgets()
        kwargs = self.categotyInterface.getCheckedCategory()
        self.load(**kwargs)

    def onResult(self, result: dict):
        data = check_result(result)
        if data is None:
            return
        vodrows = data['vodrows']
        self.totalPages = data['pageinfo']['totalpage']
        for vod in vodrows:
            if vod['isvip'] != '0':
                continue
            card = VideoCard(self)
            card.setData(vod)
            self.gridLayout.addWidget(card)
        if self.gridLayout.count() < 20:
            self.nextPage()

    def nextPage(self):
        super().nextPage()
        self.load(**self.categotyInterface.getCheckedCategory())
